import { ref, watch, watchEffect } from 'vue'
import { storeToRefs } from 'pinia'
import useInitSocket, { SocketStatus } from './init'
import useUserStore from '@/stores/modules/user'
import { ENV_CONFIG } from '@/config'

export default function useWebSocket() {
  const { token } = storeToRefs(useUserStore())
  const { status, message, connect, disconnect, reconnect } = useInitSocket({
    // url: `${import.meta.env.VITE_WS_HOST}?uid=${uid.value}&Authorization=Bearer ${token.value}`,
    url: `${(ENV_CONFIG as any)[import.meta.env.MODE].wsHost}?Authorization=Bearer ${token.value}`,
    heartBeatData: 'my heart data',
  })

  const chatMessage = ref(null)
  const socketStatusText = ref('')
  const retryConnect = () => {
    if (status.value !== SocketStatus.Connected)
      connect()
  }

  const offline = () => console.log('网络连接已断开')
  const online = () => {
    console.log('网络连接已恢复')
    retryConnect()
  }
  function addEvent() {
    window.addEventListener('offline', offline)
    window.addEventListener('online', online)
  }
  function removeEvent() {
    window.removeEventListener('offline', offline)
    window.removeEventListener('online', online)
  }

  watch(
    () => status.value,
    (newVal) => {
      if (newVal !== SocketStatus.Connected)
        socketStatusText.value = newVal
    },
  )

  watch(
    () => message.value,
    (newVal) => {
      if (newVal)
        chatMessage.value = newVal
    },
  )

  // 检测登录后就发起连接，退出后断开连接
  watchEffect(() => {
    if (token.value) {
      connect()
      addEvent()
    }
    else {
      disconnect()
      removeEvent()
    }
  })

  return {
    status,
    socketStatusText,
    chatMessage,
    retryConnect,
    reconnect,
    connect,
  }
}
